var menuUrlOfThisPage = window.document.location.pathname.substring(1);
menuUrlOfThisPage = menuUrlOfThisPage.substring(menuUrlOfThisPage.indexOf("/")+1);
var rootPathWithSlash = window.location.href.substring(0, window.location.href.length - window.location.search.length);
rootPathWithSlash = rootPathWithSlash.substring(0, rootPathWithSlash.length - menuUrlOfThisPage.length);

$(function() {
	//以下页面严格不予显示按钮
	var forbidden = ["a"//主页
					,"fmall/cardriver"//司机详细信息，代码中使用了循环查询组装数据。
	];
	var isForbidden = false;
	forbidden.forEach(function(item, index, array) {
		if (item == menuUrlOfThisPage) {
			isForbidden = true;
			return;
		}
	});
	if (!isForbidden && allowedShowAtUserAgent()) {//火狐千万不能执行这个ajax，订单页查航班会循环加载所有js。
		jQuery.getJSON(rootPathWithSlash + "report/commonExcel/getMenuUrlForExcel", function(data){
			//该放在哪个前台缓存？刷新和点开选项卡的区别。
			if (data[menuUrlOfThisPage] == null) return;
			var butt = '<input type="button" class="easyui-linkbutton" onclick="sendDataForExcel(true)"' +
					' value="导出Excel" style="float:right"/>';
			$('[onclick="cx()"]').after(butt);
		});
	}
});

function allowedShowAtUserAgent() {//已知支持IE和Chrome，不支持火狐。未测试老版的浏览器。
	var ua = navigator.userAgent;
	/*
	var IE = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; " +
			".NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; " +
			".NET4.0C; .NET4.0E; rv:11.0) like Gecko";
	var Chrome = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36";
	var FireFox = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0";
	*/
	return (ua.indexOf("Trident") > -1) || (ua.indexOf("Chrome") > -1);
}

function sendDataForExcel(useGet) {
	var pageNumber = 1;
	var pageSize = 20000;
	addLoadingMask();
	changeMaskMsg("正在获取数据");
	var formData = $("form:first").serializeObject();
	formData.page = pageNumber;
	formData.rows = pageSize;
	var dgObj = window.dg.datagrid("options");
	if (dgObj == null) {
		alert("无法获取数据，请联系后台人员");
		removeLoadingMask();
	}
	formData.sort = dgObj.sortName;
	formData.order = dgObj.sortOrder;
	$.ajax({
		url: dgObj.url,
		type: useGet ? 'GET' : 'POST',
		data: formData,
		dataType: 'json',
		success: function(result) {
			var rows = result.rows;
			if (rows.length > 0) {
				assemDataAndSend(JSON.stringify(rows));
			} else {
				alert("查询无数据");
				removeLoadingMask();
			}
		},
		error: function(xhr) {
			if (useGet && xhr.status == 405) {
				sendDataForExcel(false);
			} else {
				alert("请求失败");
				removeLoadingMask();
			}
		}
	});
}

function assemDataAndSend(rows) {
	changeMaskMsg("处理数据中，请勿操作浏览器");
	var url = window.location.href;
	$.ajax({
		type : "GET",
		url : url,
		success : function(pageCode) {
			var fix = "--------";
			var separator = fix + "entity_separator" + fix;
			var dgObj = window.dg.datagrid("options");
			var columnsCode = objectArrayToString(dgObj.columns[0]);
			var data = rows + separator + pageCode + separator + window.menuUrlOfThisPage + separator + columnsCode;
			data = pako.gzip(data);
			send(data);
		}
	});
}

function objectArrayToString(array) {
	if (array.length == 0) {
		return "[]";
	}
	var str = "[";
	array.forEach(function(item, index, array) {
		str += "{";
		for (var key in item) {
			if (typeof item[key] == "string") {
				str += key + ":'" + item[key] + "',";
			} else {
				str += key + ":" + item[key] + ",";
			}
		}
		str = str.substring(0, str.length-1) + "},";
	});
	return str.substring(0, str.length-1) + "]";
}

function send(data) {
	changeMaskMsg("数据已就绪，正在生成excel");
	var url = rootPathWithSlash + "report/commonExcel/resolvePageData";
	var xhr = new XMLHttpRequest();
	xhr.open("post", url, true);
	xhr.responseType = "blob";
	xhr.onload = function() {
		if (this.status == 200) {
			var blob = this.response;
			var header = xhr.getResponseHeader("Content-Disposition");
			var fileName = null;
			if (header != null && header.indexOf("filename") > -1) {
				fileName = header.substring(header.indexOf('="')+2, header.lastIndexOf('"'));
				fileName = decodeURI(fileName);
			} else {
				fileName = "错误信息文件[" + window.menuUrlOfThisPage + "]";
			}
			removeLoadingMask();
			downFile(blob, fileName);
		} else {
			alert("请求失败：" + xhr.status);
			removeLoadingMask();
		}
	};
	xhr.setRequestHeader("Content-Type", "application/octet-stream");
//	xhr.setRequestHeader("Content-Encoding", "gzip");
	xhr.setRequestHeader("useGzip", "Y");//避免cc服务器自动解压
	xhr.send(data);
}

function downFile(blob, fileName) {
	if (window.navigator.msSaveOrOpenBlob) {
		navigator.msSaveBlob(blob, fileName);
	} else {
		var link = document.createElement('a');
		link.href = window.URL.createObjectURL(blob);
		link.download = fileName;
		link.click();
		window.URL.revokeObjectURL(link.href);
	}
}

function addLoadingMask() {
	$("<div class=\"datagrid-mask\"></div>")
			.css({ display: "block", width: "100%", height: $(window).height() })
			.appendTo("body");
	$("<div class=\"datagrid-mask-msg\"></div>").html("正在处理，请稍候。。。")
			.appendTo("body").css({ display: "block",
			left: ($(document.body).outerWidth(true) - 190) / 2,
			top: ($(window).height() - 45) / 2 });
}

function changeMaskMsg(msg) {
	$(".datagrid-mask-msg").html(msg);
}

function removeLoadingMask() {
	$(".datagrid-mask").remove();
	$(".datagrid-mask-msg").remove();
}